package dyyx.util;

import java.io.Closeable;

import io.netty.buffer.ByteBuf;

public class CommUtil {

	private static final String SLEEP = "sleep";
	private static final int SLEEP_LEN = SLEEP.length();

	public static void main(String[] args) throws Exception {

	}
	
	
	public final static String toString(ByteBuf buf) {
		if (buf == null) {
			return null;
		}
		// 堆缓冲区
		if (buf.hasArray()) {
			return new String(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes());
		}
		// 直接缓冲区或复合缓冲区
		byte[] bytes = new byte[buf.readableBytes()];
		buf.getBytes(buf.readerIndex(), bytes);
		return new String(bytes, 0, buf.readableBytes());

	}
	
	

	public static final int getInt(String str, int def) {
		if (str == null) {
			return def;
		}
		try {
			return Integer.parseInt(str);
		} catch (Throwable e) {
			return def;
		}
	}

	public static final long getLong(String str, long def) {
		if (str == null) {
			return def;
		}
		try {
			return Long.parseLong(str);
		} catch (Throwable e) {
			return def;
		}
	}

	public static final int getIntFromSysProp(String name, int def) {
		String str = System.getProperty(name);
		return getInt(str, def);
	}

	public static final long getLongFromSysProp(String name, long def) {
		String str = System.getProperty(name);
		return getLong(str, def);
	}

	public final static void doSleep(long time) {
		if (time <= 0) {
			return;
		}
		try {
			Thread.sleep(time);
		} catch (Throwable e) {
			//
		}
	}

	public final static void close(Closeable obj) {
		if (obj == null) {
			return;
		}
		try {
			obj.close();
		} catch (Throwable e) {
			//
		}
	}

	public static long getSleepTime(String str) {
		if (str == null) {
			return 0;
		}
		if (!str.startsWith(SLEEP)) {
			return 0;
		}
		final int len = str.length();
		if (len <= SLEEP_LEN) {
			return 0;
		}
		str = str.substring(SLEEP_LEN);
		try {
			return Long.parseLong(str);
		} catch (Throwable e) {
			return 0;
		}
	}

}
